package org.jeecg.modules.peopleTask.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.peopleTask.entity.MessageLogging;
import org.jeecg.modules.peopleTask.entity.TemporaryTask;
import org.jeecg.modules.peopleTask.service.IMessageLoggingService;
import org.jeecg.modules.peopleTask.service.ITemporaryTaskService;
import org.jeecg.modules.personalTask.entity.PersonalTask;
import org.jeecg.modules.personalTask.service.IPersonalTaskService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.TemplateMessageUtil;
import org.jeecg.modules.system.util.ThreadPoolManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 临时任务
 * @Author: jeecg-boot
 * @Date:   2023-12-20
 * @Version: V1.0
 */
@Api(tags="临时任务")
@RestController
@RequestMapping("/peopleTask/temporaryTask")
@Slf4j
public class TemporaryTaskController extends JeecgController<TemporaryTask, ITemporaryTaskService> {
	@Autowired
	private ITemporaryTaskService temporaryTaskService;
	@Autowired
	private IMessageLoggingService messageLoggingService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ThreadPoolManager threadPoolManager;
	@Autowired
	private TemplateMessageUtil templateMessageUtil;
	@Autowired
	private IPersonalTaskService personalTaskService;
	
	/**
	 * 分页列表查询
	 *
	 * @param temporaryTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "临时任务-分页列表查询")
	@ApiOperation(value="临时任务-分页列表查询", notes="临时任务-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TemporaryTask temporaryTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TemporaryTask> queryWrapper = QueryGenerator.initQueryWrapper(temporaryTask, req.getParameterMap());
		Page<TemporaryTask> page = new Page<TemporaryTask>(pageNo, pageSize);
		IPage<TemporaryTask> pageList = temporaryTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getOwnerTemporaryTask")
	public Result<?> getOwnerTemporaryTask(){
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<TemporaryTask> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TemporaryTask::getAssignedTo, user.getRealname());
		wrapper.eq(TemporaryTask::getIfSuccess, 0);
		List<TemporaryTask> list = temporaryTaskService.list(wrapper);
		return Result.OK(list);
	}

	@GetMapping("/getOwnerTaskCount")
	public Result<?> getOwnerTaskCount(){
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<TemporaryTask> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TemporaryTask::getAssignedTo, user.getRealname());
		wrapper.eq(TemporaryTask::getIfSuccess, 0);
		List<TemporaryTask> list = temporaryTaskService.list(wrapper);
		LambdaQueryWrapper<PersonalTask> wrapper1 = Wrappers.lambdaQuery();
		wrapper1.eq(PersonalTask::getHeader, user.getRealname());
		wrapper1.eq(PersonalTask::getStatus, 1);
		wrapper1.eq(PersonalTask::getSign, 1);
		List<PersonalTask> list1 = personalTaskService.list(wrapper1);
		int i = list.size() + list1.size();
		return Result.OK(i);
	}
	
	/**
	 *   添加
	 *
	 * @param temporaryTask
	 * @return
	 */
	@AutoLog(value = "临时任务-添加")
	@ApiOperation(value="临时任务-添加", notes="临时任务-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TemporaryTask temporaryTask) {
		threadPoolManager.executeTask(() -> sendTemplate(temporaryTask));
		temporaryTask.setIfSuccess("0");
		temporaryTaskService.save(temporaryTask);
		return Result.OK("添加成功！");
	}

	private void sendTemplate(TemporaryTask temporaryTask) {
		MessageLogging messageLogging = new MessageLogging();
		messageLogging.setMessageType("临时任务")
				.setCarbonCopyPerson(temporaryTask.getInitiator())
				.setCarbonCopyMassage(temporaryTask.getTaskName())
				.setCarbonCopyTo(temporaryTask.getAssignedTo());
		messageLoggingService.save(messageLogging);

		LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
		wrapper.in(SysUser::getRealname, temporaryTask.getInitiator(), temporaryTask.getAssignedTo());
		List<SysUser> list = sysUserService.list(wrapper);
		String stringDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		for (SysUser sysUser : list){
			String wxOpenid = sysUser.getWxOpenid();
			if (wxOpenid != null && !wxOpenid.isEmpty()){
				templateMessageUtil.getSendMessage(wxOpenid,
						temporaryTask.getInitiator()+"发布了临时任务To:"+temporaryTask.getAssignedTo(),
						temporaryTask.getInitiator(), stringDate);
			}
		}
	}

	/**
	 *  编辑
	 *
	 * @param temporaryTask
	 * @return
	 */
	@AutoLog(value = "临时任务-编辑")
	@ApiOperation(value="临时任务-编辑", notes="临时任务-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TemporaryTask temporaryTask) {
		temporaryTaskService.updateById(temporaryTask);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "临时任务-通过id删除")
	@ApiOperation(value="临时任务-通过id删除", notes="临时任务-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		temporaryTaskService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "临时任务-批量删除")
	@ApiOperation(value="临时任务-批量删除", notes="临时任务-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.temporaryTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "临时任务-通过id查询")
	@ApiOperation(value="临时任务-通过id查询", notes="临时任务-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		TemporaryTask temporaryTask = temporaryTaskService.getById(id);
		if(temporaryTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(temporaryTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param temporaryTask
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TemporaryTask temporaryTask) {
        return super.exportXls(request, temporaryTask, TemporaryTask.class, "临时任务");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TemporaryTask.class);
    }

}
